package com.rest.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rest.core.dao.JdbcTemplateUtil;
import com.rest.core.dto.PageDTO;
import com.rest.dao.BookDao;
import com.rest.entity.Book;

@Service
@Transactional(readOnly = true)
public class BookService {

	@Autowired
	private BookDao bookDao;
	@Autowired
	private JdbcTemplateUtil jdbcTemplateUtil;

	public BookService() {
	}

	public PageDTO getList() {
		PageDTO page = new PageDTO();
		String sql = "SELECT b.id,b.book_name AS bookName,b.author FROM book  b";
		List<Map<String, Object>> list = jdbcTemplateUtil.queryForList(sql);
		page.setList(list);
		page.setTotalCount((long) 100);
		page.setTotalPages(1);
		return page;
	}

	public Book getById(Integer id) {
		return bookDao.findUniqueBy("id", id);
	}

	@Transactional(readOnly = false)
	public Book save(String bookName, String author) {
		Book entity = new Book();
		entity.setBookName(bookName);
		entity.setAuthor(author);
		bookDao.save(entity);
		Book book = new Book(entity);
		return book;
	}

	@Transactional(readOnly = false)
	public void newEntity(Integer id, String bookName, String author) {
		Book book = bookDao.findUniqueBy("id", id);
		book.setBookName(bookName);
		book.setAuthor(author);
	}

	@Transactional(readOnly = false)
	public void delEntity(Integer id) {
		bookDao.delete(id);
	}

}
